<template>
  <div class="system-role-container layout-padding">
    <div class="system-role-padding layout-padding-auto layout-padding-view">
      <div class="m-header">
        <div class="pro-name"></div>
      </div>

      <div class="table_content_changes">
        <div
          style="
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
          "
          class="button_poastion"
        >
          <div style="width: 20%">
            <el-input
              clearable
              size="default"
              placeholder="请输入文档序号"
              v-model="proName"
              :suffix-icon="Search"
            />
          </div>

          <div style="display: flex; align-items: center">
            <el-popover v-if="false" placement="bottom-start" :width="600">
              <template #reference>
                <el-button size="small" :icon="Upload" class="dr23"
                  >导入</el-button
                >
              </template>
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  padding: 10px;
                "
              >
                <el-upload
                  action="#"
                  :http-request="uploadRequest"
                  :show-file-list="false"
                  style="display: inline-block"
                  class="buttonposition"
                >
                  <el-button
                    size="small"
                    :icon="Upload"
                    type="primary"
                    class="dr23"
                    >导入部室文件</el-button
                  >
                </el-upload>

                <el-upload
                  action="#"
                  :http-request="uploadRequest2"
                  :show-file-list="false"
                  style="display: inline-block"
                  class="buttonposition"
                >
                  <el-button
                    size="small"
                    :icon="Upload"
                    type="success"
                    class="dr23"
                    >导入技术资料</el-button
                  >
                </el-upload>

                <el-upload
                  action="#"
                  :http-request="uploadRequest3"
                  :show-file-list="false"
                  style="display: inline-block"
                  class="buttonposition"
                >
                  <el-button
                    size="small"
                    :icon="Upload"
                    type="danger"
                    class="dr23"
                    >导入党建资料</el-button
                  >
                </el-upload>

                <el-upload
                  action="#"
                  :http-request="uploadRequest4"
                  :show-file-list="false"
                  style="display: inline-block"
                  class="buttonposition"
                >
                  <el-button
                    size="small"
                    :icon="Upload"
                    type="warning"
                    class="dr23"
                    >导入海外资料</el-button
                  >
                </el-upload>
              </div>
            </el-popover>

            <el-popconfirm
              v-if="false"
              @confirm="delAllRules"
              title="确定要删除吗？"
            >
              <template #reference> </template>
            </el-popconfirm>
            <el-button
              @click="downloadFile"
              size="small"
              type="success"
              class="delArr"
              :icon="Download"
              >批量导出培训记录</el-button
            >
            <el-button
              @click="newDio"
              size="small"
              type="primary"
              class="delArr"
              :icon="CirclePlus"
              >新建</el-button
            >
          </div>
        </div>
        <el-table
          :header-cell-style="{ background: '#fafbfc', color: '#333333' }"
          :data="tableRuleData"
          class="roledata"
          @selection-change="handleSelectionChangeRule"
          :height="activeHeight"
        >
          <el-table-column type="selection" />
          <el-table-column
            type="index"
            width="80"
            label="序号"
            align="center"
          />
          <el-table-column prop="file_no" label="文档序号"> </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="training_subject"
            label="培训主题"
          >
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="training_time"
            label="培训日期"
          >
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="number_participants"
            label="培训人数"
          >
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="training_hours"
            label="培训课时"
          >
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="teacher" label="主讲人">
          </el-table-column>

          <el-table-column width="250" label="操作">
            <template #default="scope">
              <span
                style="color: #1890ff; margin-right: 1em; cursor: pointer"
                size="small"
                @click="exportWordDocx_docx(scope.row)"
                >导出</span
              >
              <span
                style="color: #67c23a; margin-right: 1em; cursor: pointer"
                size="small"
                @click="edit_table(scope.row)"
                >编辑</span
              >
              <el-popconfirm
                title="确定要删除吗?"
                @confirm="confirmDeleteRule(scope.$index, scope.row)"
              >
                <template #reference>
                  <span style="color: #f56c6c; cursor: pointer">删除</span>
                </template>
              </el-popconfirm>


              
              <el-button style="margin-left: 5px"    link type="warning" 
            @click="showDioFile(scope.row)">附件</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: none" class="page_pagiation">
          <el-pagination
            v-if="false"
            v-model:current-page="pageNumRule"
            v-model:page-size="pageSizeRule"
            :page-sizes="[10, 30, 50]"
            background
            layout="total, sizes, prev, pager, next"
            :total="totalRule"
            @size-change="handleSizeChangeRule"
            @current-change="handleCurrentChangeRule"
          />
        </div>
        <el-dialog v-model="newDiog" title="" width="30%">
          <div class="table_P">
            <el-form
              size="small"
              :model="newForm"
              label-position="left"
              label-width="80px"
            >
              <div
                style="
                  font-size: 20px;
                  font-weight: bold;
                  text-align: center;
                  margin-bottom: 20px;
                "
              >
                内部培训记录
              </div>
              <div class="flex_style">
                <el-form-item label="文件编号：">
                  <el-input
                    disabled
                    style="width: 90%"
                    v-model="newForm.file_no"
                    placeholder="自动生成文件编号"
                  />
                </el-form-item>
                <el-form-item label="培训主题：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.training_subject"
                    placeholder="请输入培训主题"
                  />
                </el-form-item>
                <el-form-item label="主讲人：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.teacher"
                    placeholder="请输入主讲人"
                  />
                </el-form-item>
                <el-form-item label="预期效果：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.expected_effect"
                    placeholder="请输入预期效果"
                  />
                </el-form-item>
                <el-form-item label="参加人数：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.number_participants"
                    placeholder="请输入参加人数"
                  />
                </el-form-item>
                <el-form-item label="实到人数：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.actual_attendance"
                    placeholder="请输入实到人数"
                  />
                </el-form-item>
                <el-form-item label="培训地点：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.training_location"
                    placeholder="请输入培训地点"
                  />
                </el-form-item>
                <el-form-item style="width: 247px" label="培训时间：">
                  <el-date-picker
                    style="width: 90%"
                    v-model="newForm.training_time"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="请选择日期"
                    size="small"
                  />
                </el-form-item>
                <el-form-item label="培训对象：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.training_target"
                    placeholder="请输入培训对象"
                  />
                </el-form-item>

                <el-form-item label="培训方式：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.training_method"
                    placeholder="请输入培训方式"
                  />
                </el-form-item>

                <el-form-item label="培训课时：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.training_hours"
                    placeholder="请输入培训课时"
                  />
                </el-form-item>

                <el-form-item label="实施部门：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.implementing_department"
                    placeholder="请输入实施部门"
                  />
                </el-form-item>

                <el-form-item label="责任人：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.person_charge"
                    placeholder="请输入责任人"
                  />
                </el-form-item>

                <el-form-item label="考核方式：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.assessment_method"
                    placeholder="请输入考核方式"
                  />
                </el-form-item>

                <el-form-item label="合格人数：">
                  <el-input
                    style="width: 90%"
                    v-model="newForm.qualified_participants"
                    placeholder="请输入合格人数"
                  />
                </el-form-item>
              </div>

              <el-form-item label="培训内容：">
                <el-input
                  style="width: 95%"
                  resize="none"
                  :rows="4"
                  type="textarea"
                  v-model="newForm.training_content"
                  placeholder="请输入"
                />
              </el-form-item>

              <el-form-item style="position: relative" label="参加人员：">
                <el-input
                  style="width: 95%"
                  resize="none"
                  :rows="4"
                  type="textarea"
                  v-model="newForm.participants"
                  placeholder="请输入"
                />

                <div
                  v-if="showFile == 'showFile1'"
                  style="position: absolute; right: 35px; bottom: 2px"
                >
                  <el-popover
                    placement="top-start"
                    :teleported="false"
                    :width="200"
                    trigger="click"
                  >
                    <el-table :data="newUploadFileTable" size="small">
                      <el-table-column
                        label="文件名称"
                        prop="name"
                      ></el-table-column>
                    </el-table>
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: flex-end;
                        margin-top: 10px;
                      "
                    >
                      <el-upload
                        :icon="Download"
                        class="upload-demo"
                        action="#"
                        :show-file-list="false"
                        :http-request="uploadTable"
                      >
                        <el-button size="small" type="success"
                          >上传文件</el-button
                        >
                      </el-upload>
                    </div>
                    <template #reference>
                      <el-icon
                        :color="newUploadFileTable.length > 0 ? 'green' : ''"
                        size="20"
                        ><Warning
                      /></el-icon>
                    </template>
                  </el-popover>
                </div>

                <div
                  v-if="showFile == 'showFile2'"
                  style="position: absolute; right: 35px; bottom: 2px"
                >
                  <el-popover
                    placement="top-start"
                    :teleported="false"
                    :width="350"
                    trigger="click"
                  >
                    <el-table :data="newUploadFileTable" size="small">
                      <el-table-column
                        width="150"
                        show-overflow-tooltip
                        label="文件名称"
                        prop="name"
                      ></el-table-column>
                      <el-table-column width="80" label="文件大小">
                        <template #default="scope"
                          >{{ convertFileSize(scope.row.sign_in_sheet_size_inBytes)
                          }}</template
                        >
                      </el-table-column>
                      <el-table-column label="操作">
                        <template #default="scope">
                          <span
                            style="
                              color: #1890ff;
                              margin-right: 1em;
                              cursor: pointer;
                            "
                            size="small"
                            @click="previewRule(scope.row)"
                            >下载</span
                          >
                          <span
                            @click="delNewTable(scope.row, scope.$index)"
                            style="color: #189eff; cursor: pointer"
                            >删除</span
                          >

                        </template>
                      </el-table-column>
                    </el-table>

                    <template #reference>
                      <el-icon
                        :color="newUploadFileTable.length > 0 ? 'green' : ''"
                        size="20"
                        ><Warning
                      /></el-icon>
                    </template>
                  </el-popover>
                </div>
              </el-form-item>

              <el-form-item label="效果评价：">
                <el-input
                  style="width: 95%"
                  resize="none"
                  :rows="4"
                  type="textarea"
                  v-model="newForm.effect_evaluation"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-form>

            <div
              style="
                display: flex;
                align-items: center;
                justify-content: flex-end;
                margin-top: 20px;
              "
            >
              <el-button @click="new_Commit" size="small" type="primary"
                >提交</el-button
              >
            </div>
          </div>
        </el-dialog>



        <el-dialog @close="handleClose()" v-model="dialogFiles" title="附件列表" width="43%">
      <el-table size="default" :data="dioFiles" class="roledata" height="400">
        <el-table-column width="310" show-overflow-tooltip prop="file_name" label="附件名称">
        </el-table-column>
        <el-table-column width='100' prop="user_account" label="文件大小">
          <template #default="scope">
            <el-tag style="margin-right: 5px; margin-bottom: 5px" size="small" type="success">
            
              {{convertFileSize(scope.row.file_size_inBytes)}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="上传时间">
        </el-table-column>

        <el-table-column width="150" label="操作">
          <template #default="scope">
            <span style="
                color: #67c23a;
                margin-right: 1em;
                cursor: pointer;
                font-size: 12px;
              " size="small" @click="viewFile( scope.row)">
              预览
            </span>
            <span style="
                color: #1890ff;
                margin-right: 1em;
                cursor: pointer;
                font-size: 12px;
              " size="small" @click="downLoadFileTable(scope.$index, scope.row)">
              下载
            </span>
            <el-popconfirm title="确定要删除吗?" @confirm="delFile(scope.row)">
              <template #reference>
                <span style="color: #f56c6c; cursor: pointer; font-size: 12px">删除</span>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex;
    align-items: center;
    margin-top: 20px;
    padding-right: 10px;
    justify-content: flex-end;position: relative;" class="upLoad">
       
        <el-upload :icon="Download" class="upload-demo" action="#" :show-file-list="false" :http-request="uploadTableFiles">
          <el-button  size="small" type="success">上传文件</el-button>
        </el-upload>
      </div>
    </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup name="systemRole">
import { defineAsyncComponent, reactive, onMounted, ref, watch } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  Search,
  CirclePlus,
  Upload,
  Download,
  Delete,
  Warning,
} from "@element-plus/icons-vue";
import { useProjectStore } from "../../stores/project";
import { storeToRefs } from "pinia";
import {
  DeleteUnit,
  AddUnit,
  GetUnits,
  impMarjor,
  
  getOptionLeader,
  getOptionTeam,
  GetProjectUnifiedRegulationFiles,
  UploadDepartmentFiles,
  DownloadDepartmentFile,
  DeleteDepartmentFile,
  AddProjectNotice,
  ModifyProjectNoticeState,
  GetAllProjectNotices,
  GetDepartmentFiles,
  GetAllTrainingRecord,
  SaveTrainingRecord,
  UploadTrainingRecordSignInSheet,
  UpdateTrainingRecord,
  DelTrainingRecord,
  DelTrainingRecordSignInSheet,
  DownLoadTrainingRecordSignInSheet,
  GetTrainingRecordAttachFiles,
  UploadTrainingRecordAttachFiles,
  DownloadTrainingRecordAttachFile,
  DeleteTrainingRecordAttachFile
} from "../../api/projectManage/projectList";
import JSZipUtils from "jszip-utils";
import docxtemplater from "docxtemplater";
import { saveAs } from "file-saver";
import JSZip from "pizzip";
import ImageModule from "docxtemplater-image-module-free";
import { ClickOutside as vClickOutside } from "element-plus";
import checkFile from "/@/utils/checkFile";
let store = useProjectStore();

let { projectInfo } = storeToRefs(store);

let proName = ref("");

let newUpLoadFile = ref({});

let newUploadFileTable = ref([]);



let delFile =async (row) => {
  await DeleteTrainingRecordAttachFile({ id: row.Id });
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    getFileTable(dioRow.value);
}

let downLoadFileTable = async(index,row) => {
  let res = await DownloadTrainingRecordAttachFile({ remote_url: row.remote_url });

    let filename = res.headers; //下载后文件名
    let filename2 = ""; //下载后文件名
    filename = filename["content-disposition"];
    filename = window.decodeURI(filename);
    filename2 = filename.split(";")[1].split("filename*=UTF-8''")[1];
    filename = filename.split(";")[1].split("filename=")[1];
    const link = document.createElement("a"); // 创建a标签
    const blo = new Blob([res.data], { type: res.data.type }); // 设置下载格式
    link.style.display = "none";
    const url = window.URL.createObjectURL(blo);
    link.href = url;
    if (filename == undefined) {
      filename = filename2;
    }
    link.download = filename;

    // link.setAttribute('download', "fileName")
    document.body.appendChild(link);
    link.click(); // 触发下载
    window.URL.revokeObjectURL(url); // 释放掉blob对象
    document.body.removeChild(link);
}
let viewFile = (row) => {
  console.log(row)
  checkFile("", row);
}



let uploadTableFiles =async (file) => {
  let fromData = new FormData();
    fromData.append("file", file.file);
   await UploadTrainingRecordAttachFiles(
      fromData,
      dioRow.value.oid,
     
    );

    ElMessage({
      message: "上传成功",
      type: "success",
    });
    getFileTable(dioRow.value);
}

// 前端显示上传文件  （假上传）
let uploadTable = async (file) => {
  newUpLoadFile.value = file;

  newUploadFileTable.value = [
    {
      name: "培训记录签到-附件1",
    },
  ];
  ElMessage({
    message: "上传成功",
    type: "success",
  });
};

// 删除表格数据内容
let delNewTable = async (row, index) => {
  newUpLoadFile.value = {};
  newUploadFileTable.value = [];
  await DelTrainingRecordSignInSheet({ ...row });
  showFile.value = "showFile1";
  ElMessage.success("删除成功");
};

// 导出文件
let exportWordDocx_docx = (obj) => {
  // 文件相对路径
  const url = "/test2.docx";
  JSZipUtils.getBinaryContent(url, (err, data) => {
    if (err) {
      ElMessage.error("导出报告出错");
      console.log("err:", err);
      return;
    }
    let zip = new JSZip(data);
    const Docxtemplater = docxtemplater;
    const imageOptions = {
      centered: false,
      getImage(tagValue, tagName) {
        return new Promise(function (resolve, reject) {
          JSZipUtils.getBinaryContent(tagValue, function (error, content) {
            if (error) {
              return reject(error);
            }
            return resolve(content);
          });
        });
      },
      getSize(img, tagValue, tagName) {
        // 非固定大小（这里是设置宽度最大为500px的图片）
        return new Promise(function (resolve, reject) {
          let image = new Image();
          image.src = tagValue;
          let imgWidth, imgHeight, scale;
          image.onload = function () {
            imgWidth = image.width;
            imgHeight = image.height;
            scale = 0;
            if (imgWidth > 500) {
              scale = 500 / imgWidth;
              imgWidth = 500;
              imgHeight = imgHeight * scale;
            }
            resolve([imgWidth, imgHeight]);
          };
          image.onerror = function (e) {
            console.log("img, tagValue, tagName : ", img, tagValue, tagName);
            reject(e);
          };
        });
      },
    };

    const nullGetter = (part, scopeManager) => {
      if (!part.module) {
        return "";
      }
    };

    let doc = new Docxtemplater(zip, {
      linebreaks: true,
      nullGetter: nullGetter,
      modules: [new ImageModule(imageOptions)],
    });
    // 定义需要导出的数据  是否模板一致
    let reportInfo = {};
    obj.training_content_arr = obj.training_content.split("/n");
    obj.create_time = obj.create_time.substring(
      0,
      obj.create_time.indexOf(" ")
    );
    reportInfo = { ...obj };
    // 导入
    doc.resolveData({ ...reportInfo }).then(() => {
      doc.render();
      let out = doc.getZip().generate({
        type: "blob",
        MimeType:
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      });
      // 定义文件导出名称
      // saveAs(out, "内部培训记录表.docx");
      saveAs(out, `${obj.file_no}.docx`);
    });
  });
};

// 提交新文件内容
let new_Commit = async () => {
  // 是否是修改 还是提交  判断是否有oid
  if (newForm.value.oid) {
    let obj = {
      ...newForm.value,
      fileOid: newForm.value.oid,
    };
    delete obj.oid;
    await UpdateTrainingRecord(obj);

    if (newUploadFileTable.value.length > 0) {
      let fromData = new FormData();
      fromData.append("file", newUpLoadFile.value.file);
      await UploadTrainingRecordSignInSheet(obj.fileOid, fromData);
    }
    gettableRuleDataData();
    ElMessage.success("修改成功");
    newDiog.value = false;
    newUpLoadFile.value = {};
    newUploadFileTable.value = [];
  } else {
    let res = await SaveTrainingRecord(newForm.value);
    if (newUploadFileTable.value.length > 0) {
      let fromData = new FormData();
      fromData.append("file", newUpLoadFile.value.file);
      await UploadTrainingRecordSignInSheet(res.data, fromData);
    }

    gettableRuleDataData();
    ElMessage.success("保存成功");

    newDiog.value = false;
    newUpLoadFile.value = {};
    newUploadFileTable.value = [];
  }
};

// 下载文件
let downloadFile = async () => {
  if (delArrRule.value.length == 0) {
    ElMessage.warning("请选择培训记录");
    return false;
  }
  let res = await DownLoadTrainingRecordSignInSheet({
    fileOids: delArrRule.value.map((v) => v.oid),
  });

  let filename = res.headers; //下载后文件名
  let filename2 = ""; //下载后文件名
  filename = filename["content-disposition"];
  filename = window.decodeURI(filename);
  filename2 = filename.split(";")[1].split("filename*=UTF-8''")[1];
  filename = filename.split(";")[1].split("filename=")[1];
  const link = document.createElement("a"); // 创建a标签
  const blo = new Blob([res.data], { type: res.data.type }); // 设置下载格式
  link.style.display = "none";
  const url = window.URL.createObjectURL(blo);
  console.log(url);
  link.href = url;
  if (filename == undefined) {
    filename = filename2;
  }
  link.download = filename;

  // link.setAttribute('download', "fileName")3
  document.body.appendChild(link);
  link.click(); // 触发下载
  window.URL.revokeObjectURL(url); // 释放掉blob对象
  document.body.removeChild(link);
  ElMessage({
    message: "成功生成文件",
    type: "success",
  });
};

// 编辑表单
let edit_table = async (data) => {
  if (
    data.sign_in_sheet_remote_url &&
    data.sign_in_sheet_remote_url.length > 0
  ) {
    
    showFile.value = "showFile2";
    newUploadFileTable.value = [
      {
        ...data,
        name: "培训记录签到-附件1",
        remote_url: data.sign_in_sheet_remote_url,
      },
    ];
    console.log(newUploadFileTable.value);
  } else {
    newUploadFileTable.value = [];
     
    showFile.value = "showFile1";
  }

  newForm.value = { ...data };

  newDiog.value = true;
};

// 表单数据源
let newForm = ref({
  file_no: "",
  training_subject: "",
  teacher: "",
  expected_effect: "",
  number_participants: "",
  actual_attendance: "",
  training_location: "",
  training_time: "",
  training_target: "",
  training_method: "",
  training_hours: "",
  implementing_department: "",
  person_charge: "",
  assessment_method: "",
  qualified_participants: "",
  training_content: "",
  participants: "",
  effect_evaluation: "",
  modify_user: JSON.parse(localStorage.getItem("userMessage")).user_name,
});

let newDiog = ref(false);
let showFile = ref("");

// 新建弹窗
let newDio = () => {

  showFile.value = "showFile1";
  newForm.value = {
    file_no: "",
    training_subject: "",
    teacher: "",
    expected_effect: "",
    number_participants: "",
    actual_attendance: "",
    training_location: "",
    training_time: "",
    training_target: "",
    training_method: "",
    training_hours: "",
    implementing_department: "",
    person_charge: "",
    assessment_method: "",
    qualified_participants: "",
    training_content: "",
    participants: "",
    effect_evaluation: "",
    modify_user: JSON.parse(localStorage.getItem("userMessage")).user_name,
  };
  newUpLoadFile.value = {};
  newUploadFileTable.value = [];
  newDiog.value = true;
};



// 前端名称搜索逻辑
watch(proName, async () => {
  if (proName.value) {
    let res = await GetAllTrainingRecord();
    let data = JSON.parse(JSON.stringify(res));
    tableRuleData.value = data.filter((v) => v.file_no.includes(proName.value));
  } else {
    // gettableRuleDataData();
    getFinallyData()
  }
});





let tableRuleData = ref([]);




let gettableRuleDataData = async (data) => {
  // 获取所有培训内容
  let res = await GetAllTrainingRecord(data);
  
  let lastYear = "";
  let index = 0;
  // 根据实际进行排序
  let sortData = res.sort((a, b) => {
    return new Date(a.training_time) - new Date(b.training_time);
  });
  // 排序后对格式进行重构
  sortData.forEach((v) => {
    if (new Date(v.training_time).getFullYear() == lastYear) {
      index++;
      v.sortIndex = `${new Date(v.training_time).getFullYear()}-${index}`;
    } else {
      index = 1;
      v.sortIndex = `${new Date(v.training_time).getFullYear()}-${index}`;
    }
    lastYear = new Date(v.training_time).getFullYear();
  });

  // 对每个数据的序号进行重写
  sortData.forEach(async (v, i) => {
    let obj = {
      ...v,
      file_no: `ED-TR-${v.sortIndex}`,
      fileOid: v.oid,
    };
    delete obj.oid;
    // 修改每个数据
    await UpdateTrainingRecord(obj);
    if (i == sortData.length - 1) {
      getFinallyData(data);
    }
  });
};


let getFinallyData = async (data) => {
  // 这里的逻辑和上面的逻辑一样， 需要进行递归执行
  let res = await GetAllTrainingRecord(data);
  let lastYear = "";
  let index = 0;
  let sortData = res.sort((a, b) => {
    return new Date(a.training_time) - new Date(b.training_time);
  });
  sortData.forEach((v) => {
    // 如果是同一年，序号+1，否则从1开始
    if (new Date(v.training_time).getFullYear() == lastYear) {
      index++;
      v.sortIndex = `${new Date(v.training_time).getFullYear()}-${index}`;
    } else {
      index = 1;
      v.sortIndex = `${new Date(v.training_time).getFullYear()}-${index}`;
    }
    lastYear = new Date(v.training_time).getFullYear();
  });

  tableRuleData.value = sortData;
};


let tableDataPro = ref([]);

let file_type = ref(null)
let handleClose= () => {
  file_type.value = null
}


let getOptions = async (data) => {
  let option_Team = await getOptionTeam(data);
  let option_Leader = await getOptionLeader(data);
  userOptionsleader.value = option_Leader;
  optionsNewteam_leader.value = option_Team;
};

let delArrRule = ref([]);
let handleSelectionChangeRule = (val) => {
  delArrRule.value = val;
};



let dioRow = ref({})
let dialogFiles = ref(false);
let dioFiles= ref([])
let getFileTable =async (row) => {
  let res = await GetTrainingRecordAttachFiles({
      training_record_oid: row.oid,
    });
    dioFiles.value  = res
}

let showDioFile = (row) => {

  dioRow.value = row;
  dialogFiles.value = true;
  getFileTable(row);
}



let previewRule = async (row) => {
  console.log(row);
  let res = await DownloadDepartmentFile({ remote_url: row.remote_url });

  let filename = res.headers; //下载后文件名
  let filename2 = ""; //下载后文件名
  filename = filename["content-disposition"];
  filename = window.decodeURI(filename);
  filename2 = filename.split(";")[1].split("filename*=UTF-8''")[1];
  filename = filename.split(";")[1].split("filename=")[1];
  const link = document.createElement("a"); // 创建a标签
  const blo = new Blob([res.data], { type: res.data.type }); // 设置下载格式
  link.style.display = "none";
  const url = window.URL.createObjectURL(blo);
  console.log(url);
  link.href = url;
  if (filename == undefined) {
    filename = filename2;
  }
  link.download = filename;

  // link.setAttribute('download', "fileName")3
  document.body.appendChild(link);
  link.click(); // 触发下载
  window.URL.revokeObjectURL(url); // 释放掉blob对象
  document.body.removeChild(link);
  ElMessage({
    message: "成功生成文件",
    type: "success",
  });
};



let confirmDeleteRule = async (index, row) => {
  // 业务有变动，设置if留有余量
  if (true) {
    await DelTrainingRecord({ ...row });
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    gettableRuleDataData();
  }
};
let uploadRequest = async (uploadFile) => {
  let formData = new FormData();
  //传给后台接收的名字 file
  formData.append("file", uploadFile.file);
  await UploadDepartmentFiles(formData, "部室文件");
  ElMessage({
    message: "上传成功",
    type: "success",
  });
  gettableRuleDataData();
};


let convertFileSize =(sizeInBytes) => {
  
    if (sizeInBytes >= 100000) {
        // 如果文件大小大于或等于100KB，则转换为MB
        return (sizeInBytes / (1024 * 1024)).toFixed(2) + ' MB';
    } else {
        // 如果文件大小小于100KB，则保留为KB
        return (sizeInBytes / 1024).toFixed(2) + ' KB';
    }
}


let uploadRequest2 = async (uploadFile) => {
  let formData = new FormData();
  //传给后台接收的名字 file
  formData.append("file", uploadFile.file);
  await UploadDepartmentFiles(formData, "技术资料");
  ElMessage({
    message: "上传成功",
    type: "success",
  });
  gettableRuleDataData();
};

let uploadRequest3 = async (uploadFile) => {
  let formData = new FormData();
  //传给后台接收的名字 file
  formData.append("file", uploadFile.file);
  await UploadDepartmentFiles(formData, "党建资料");
  ElMessage({
    message: "上传成功",
    type: "success",
  });
  gettableRuleDataData();
};

let uploadRequest4 = async (uploadFile) => {
  let formData = new FormData();
  //传给后台接收的名字 file
  formData.append("file", uploadFile.file);
  await UploadDepartmentFiles(formData, "海外资料");
  ElMessage({
    message: "上传成功",
    type: "success",
  });
  gettableRuleDataData();
};

let dataSData = ref([]);

let activeHeight = ref(0);

let getMarjorProData = async (data) => {
  let res = await GetUnits(data);
  if (res) {
    dataSData.value = res;
  } else {
    dataSData.value = [];
  }
};

let proData = ref({});

let getNoticeDataTabel = ref([]);
let getNotice = async (data) => {
  let res = await GetAllProjectNotices(data);
  getNoticeDataTabel.value = res;
};

let userOptionsleader = ref([]);
let optionsNewteam_leader = ref([]);

// 页面加载时
onMounted(() => {
  // gettableRuleDataData();
  getFinallyData()
  activeHeight.value =
    document.querySelector(".system-role-padding").clientHeight - 100;
  window.addEventListener("resize", () => {
    activeHeight.value =
      document.querySelector(".system-role-padding").clientHeight - 100;
  });
});
</script>

<style scoped lang="scss">
.m-header {
  display: flex;
  align-items: center;
}
.m-header .pro-name {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.m-header .el-input {
  width: 300px;
}
.m-header .el-button {
  margin-right: 10px;
}

.system-role-container {
  .system-role-padding {
    padding: 15px;
    .el-table {
      flex: 1;
    }
  }
}
.button_footer {
  display: flex;
  flex-direction: row-reverse;
  width: 100%;
}
.table_content {
  margin-top: 20px;
}

::v-deep(.el-table--large .el-table__cell) {
  padding: 6px 0;
}

.table_box {
  padding: 20px 50px;
}

.button_poastion_flex_iem {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  flex-direction: row-reverse;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.el-tabs--right .el-tabs__content,
.el-tabs--left .el-tabs__content {
  height: 100%;
}

.backgroun_border {
  // 	::v-deep .el-tabs__header {
  //     margin-top: 39px;
  //   }
}

::v-deep(.el-tabs__item::after) {
  position: absolute;
  content: " ";
  top: 0;
  width: 2px;
  height: 100%;
  background: #eee;
  right: 0;
}

.table_P {
  padding: 10px 20px;
  // border: 1px solid #eee;
  border-radius: 5px;
}
.flex_style {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
}
</style>
